<template>
  <div class="set_wrap">
    <div class="head_but">
      <el-form :inline="true">
        <el-form-item>
          <el-button size="mini" type="primary" @click="getList">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabbleList">
      <!-- 表单结构图 -->
      <div class="fatherform">
        <el-table
          height="680"
          :data="tableData"
          border=""
          stripe
          style="width: 100%"
          row-key="id"
          :indent="20"
          size="mini"
          :expand-row-keys="defualtNodeList"
          :header-cell-style="{ background: '#eff3f8', color: '#606266' }"
          :tree-props="{ children: 'children' }"
        >
          <el-table-column width="300" prop="title" label="标题">
            <template slot-scope="scope">
              <i :class="'iconfont' + ' ' + scope.row.icon" style="font-size: 12px"></i>
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="tableName" label="表名"></el-table-column>
          <el-table-column prop="fieldName" label="字段名"></el-table-column>
          <el-table-column prop="isEnable" :formatter="isEnableformatter" label="数据类型"></el-table-column>
          <el-table-column prop="sort" label="排序"></el-table-column>
          <el-table-column prop="value" label="值"></el-table-column>
          <el-table-column align="center" label="操作" width="450">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" plain @click="openDialog(scope.row, 1)">新增</el-button>
              <el-button size="mini" type="success" plain @click="openDialog(scope.row, 2)">编辑</el-button>
              <el-button
                v-if="scope.row.hierarchy && scope.row.hierarchy !== '/'"
                size="mini"
                type="danger"
                plain
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 新增/编辑字典弹窗 -->
    <el-dialog title="新增/编辑字典" width="700px" :close-on-click-modal="false" :visible.sync="dialogVisible">
      <el-form :rules="dicFormDataRules" ref="dicFormData" :model="dicFormData" label-width="120px">
        <el-form-item label="标题(中文名)" prop="title">
          <el-input v-model="dicFormData.title" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item v-if="['0', '1'].indexOf(dicFormData.isEnable) !== -1" label="名称(英文名)" prop="name">
          <el-input v-model="dicFormData.name" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="['0', '1'].indexOf(dicFormData.isEnable) !== -1" label="表名" prop="tableName">
          <el-input v-model="dicFormData.tableName" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="['0', '1'].indexOf(dicFormData.isEnable) !== -1" label="字段名" prop="fieldName">
          <el-input v-model="dicFormData.fieldName" clearable></el-input>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-radio-group v-model="dicFormData.isEnable">
            <el-radio label="0">目录</el-radio>
            <el-radio label="1">值</el-radio>
            <el-radio label="2">键值</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dicFormData.isEnable === '1'" label="值" prop="value">
          <el-input v-model="dicFormData.value" clearable></el-input>
        </el-form-item>
        <template v-else-if="dicFormData.isEnable === '2'">
          <template v-for="(item, index) in dicFormData.keyValues">
            <el-row :key="item.uuid" :gutter="10">
              <el-col :span="8">
                <el-form-item label="键">
                  <el-input v-model="item.fieldKey"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label-width="60px" label="值">
                  <el-input v-model="item.fieldValue"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label-width="50px" label="排序">
                  <el-input v-model="item.sort"></el-input>
                </el-form-item>
              </el-col>
              <!-- 最后一个再显示 -->
              <el-col :span="3" v-if="index === dicFormData.keyValues.length - 1">
                <el-button type="primary" plain @click="addKeyValues">新增</el-button>
              </el-col>
              <!-- 只剩一个不显示 -->
              <el-col :span="3" v-if="dicFormData.keyValues.length > 1">
                <el-button type="danger" plain @click="delKeyValues(item)">删除</el-button>
              </el-col>
            </el-row>
          </template>
        </template>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="dicFormData.sort"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addEditSubmit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPage,
  webConfigAddition,
  webConfigGetById,
  webConfigUpdate,
  webConfigDelete
} from '@/apiList/dataDictionary.js'
import { toTree, getgenFunclist } from '@/utils/jcore/tree.js'

import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'dataDictionary',
  data() {
    return {
      tableData: [],
      defualtNodeList: [],
      dialogVisible: false,
      openType: 1,
      dicFormData: {
        title: '',
        tableName: '',
        fieldName: '',
        name: '',
        sort: 1,
        isEnable: '0',
        comments: '',
        value: '',
        keyValues: []
      },
      dicFormDataRules: {
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
        tableName: [{ required: true, message: '请填写表名', trigger: 'blur' }],
        fieldName: [{ required: true, message: '请填写字段名', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initFormData()
    this.getList()
  },
  methods: {
    // 拉取列表获得扁平数组
    getList() {
      this.tableData = []
      getPage({}).then((res) => {
        if (res && res.length) {
          this.tableData = toTree(getgenFunclist(res), {
            id: 'mid',
            children: 'children',
            pid: 'pid'
          })
        }
      })
    },
    initFormData(isEnable) {
      this.dicFormData = {
        title: '',
        tableName: '',
        fieldName: '',
        name: '',
        sort: 1,
        isEnable: isEnable || '0',
        comments: '',
        value: '',
        keyValues: []
      }

      this.dicFormData.keyValues.push({
        uuid: uuidv4(),
        fieldKey: '',
        fieldValue: '',
        sort: ''
      })
    },
    openDialogHandler() {
      this.dicFormDataRules = {
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
        tableName: [{ required: true, message: '请填写表名', trigger: 'blur' }],
        fieldName: [{ required: true, message: '请填写字段名', trigger: 'blur' }]
      }
    },
    // 打开新增/编辑弹窗 type 1新增 2编辑
    async openDialog(row, type) {
      this.openType = type
      this.dialogVisible = true
      this.$nextTick(() => {
        this.initFormData()
        try {
          // this.$refs.dicFormData.resetFields()
          this.$refs.dicFormData.clearValidate()
        } catch (err) {
          console.log(err)
        }
        if (type == 2) {
          this.getConfigInfo(row.id)
        } else {
          this.dicFormData.pid = row.id || ''
        }
      })
    },
    // 获取详情
    getConfigInfo(id) {
      webConfigGetById(`id=${id}`).then((res) => {
        if (res && Object.keys(res).length > 0) {
          this.dicFormData = res
          this.dicFormData.isEnable = this.dicFormData.isEnable.toString()
          if (this.dicFormData.keyValues && this.dicFormData.keyValues.length) {
            // 补充uuid 避免删除错乱
            this.dicFormData.keyValues.forEach((n) => {
              n.uuid = uuidv4()
            })
          } else {
            this.$set(this.dicFormData, 'keyValues', [
              {
                uuid: uuidv4(),
                fieldKey: '',
                fieldValue: '',
                sort: ''
              }
            ])
          }
        }
      })
    },
    isEnableformatter(row) {
      return row.isEnable === 0 ? '目录' : '值'
    },
    //保存
    addEditSubmit() {
      //键值需要验证键值是否填写完整
      if (this.dicFormData.isEnable === '2') {
        let pass = this.verifyKeyValues()
        if (!pass) {
          return this.$message.warning('请将键值对补充完整!')
        }
      }
      // 表单验证
      this.$refs.dicFormData.validate((val) => {
        if (val) {
          if (this.openType == 1) {
            this.addData()
          } else if (this.openType == 2) {
            this.updateData()
          }
        } else {
          return false
        }
      })
    },
    updateData() {
      this.verifyBeforeSubmission()
      webConfigUpdate(this.dicFormData).then((res) => {
        if (res) {
          this.clearDataStatus()
        }
      })
    },
    // 新增
    addData() {
      this.verifyBeforeSubmission()
      if (this.dicFormData.id) {
        delete this.dicFormData.id
      }
      webConfigAddition(this.dicFormData).then((res) => {
        if (res) {
          this.clearDataStatus()
        }
      })
    },
    clearDataStatus() {
      this.dialogVisible = false
      this.initFormData()
      this.getList()
    },
    //删除
    deleteData(row) {
      this.$confirm('此操作将删除该数据及数据子项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          webConfigDelete(`id=${row.id}`).then((res) => {
            if (res) {
              this.$message.success('删除成功')
              this.clearDataStatus()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增键值
    addKeyValues() {
      if (this.dicFormData.keyValues && this.dicFormData.keyValues.length) {
        let pass = this.verifyKeyValues()
        if (pass) {
          this.dicFormData.keyValues.push({
            uuid: uuidv4(),
            fieldKey: '',
            fieldValue: '',
            sort: ''
          })
        } else {
          this.$message.warning('请将前面的键值对补充完整再添加!')
        }
      }
    },
    // 删除键值
    delKeyValues(item) {
      if (this.dicFormData.keyValues && this.dicFormData.keyValues.length) {
        this.dicFormData.keyValues = this.dicFormData.keyValues.filter((n) => n.uuid !== item.uuid)
      }
    },
    // 验证键值对数据是否填写完整
    verifyKeyValues() {
      if (!this.dicFormData.keyValues || !this.dicFormData.keyValues.length) return false
      let pass = true
      // 只验证键值排序
      this.dicFormData.keyValues.forEach((n) => {
        let verifyKes = ['fieldKey', 'fieldValue', 'sort']
        for (let key in n) {
          if (verifyKes.indexOf(key) !== -1) {
            verifyKes = verifyKes.filter((n) => n !== key)
            if (!/^[\s\S]*.*[^\s][\s\S]*$/.test(n[key])) {
              pass = false
            }
          }
        }
        if (verifyKes.length) {
          pass = false
        }
      })
      return pass
    },
    // 在提交前对提交数据进行处理
    verifyBeforeSubmission() {
      switch (this.dicFormData.isEnable) {
        case '0': {
          this.dicFormData.keyValues = []
          this.dicFormData.value = ''
          break
        }
        case '1': {
          this.dicFormData.keyValues = []
          break
        }
        case '2': {
          this.dicFormData.value = ''
          break
        }
        default:
          break
      }
    }
  },
  watch: {
    'dicFormData.isEnable': {
      handler(newVal) {
        if (newVal === '2') {
          this.dicFormDataRules = {
            title: [{ required: true, message: '请填写标题', trigger: 'blur' }]
          }
        }
        if (newVal === '1') {
          this.dicFormDataRules = {
            title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
            value: [{ required: true, message: '请填写值', trigger: 'blur' }]
          }
        } else if (newVal === '0') {
          this.dicFormData.value = ''
          this.dicFormDataRules = {
            title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
            name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
            tableName: [{ required: true, message: '请填写表名', trigger: 'blur' }],
            fieldName: [{ required: true, message: '请填写字段名', trigger: 'blur' }]
          }
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.set_wrap {
  padding: 15px 20px;
}
.RootBox {
  height: 100%;
  padding-left: 22px;
  background-color: #fff;
}
.mbnav {
  background-color: #fff;
  .mbnavson {
    height: 51px;
    line-height: 51px;
    border-bottom: 1px solid #4285f4;
  }

  .mobile {
    line-height: 21px;
    margin-right: 25px;
  }
  .el-button--mini {
    font-size: 16px;
  }
  /deep/ .el-breadcrumb__separator[class*='icon'] {
    color: #4285f4;
  }
  /deep/.el-breadcrumb__inner {
    color: #4285f4 !important;
    font-size: 14px;
  }
}
.hander {
  height: 40px;
  width: 100%;
  background-color: #fff;
  line-height: 40px;
  border-bottom: 1px #f3f3f3 solid;
  .handerspan {
    line-height: 30px;
    font-size: 16px;
    font-weight: 600;
    color: #4285f4;
  }
}
.head_but {
  margin-top: 12px;
}
/deep/.dialog-footer {
  // text-align: center;
  display: flex;
  justify-content: center;
}
</style>
